package com.vincent.kdp.ui.commodity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.vincent.baseapp.util.SPUtil;
import com.vincent.baseapp.util.view.LoadingView;
import com.vincent.kdp.Activity.GetGoodsDetailActivity;
import com.vincent.kdp.Activity.GoodsDetailActivity;
import com.vincent.kdp.R;
import com.vincent.kdp.adapter.CommodityListAdapter;
import com.vincent.kdp.bean.Paginator;
import com.vincent.kdp.http.RequestCallBack;
import com.vincent.kdp.ui.bean.response.CommodityListOut;
import com.vincent.kdp.ui.decoration.DividerItemDecoration;
import com.vincent.kdp.ui.fragment.repository.CommodityRepository;
import com.vincent.kdp.util.BaseParam;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CommodityListActivity extends AppCompatActivity {


    @Bind(R.id.back_img)
    ImageView mBackImg;
    @Bind(R.id.toolbar_center_tv)
    TextView mToolbarCenterTv;

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.SwipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;


    public int pageNum = 1;//请求页数，默认请求第一条
    public boolean hasNext = true;

    boolean isLoading;
    private List<CommodityListOut.DataBean.ListBean> data = new ArrayList<>();
    private CommodityListAdapter adapter = new CommodityListAdapter(this, data);
    private CommodityRepository commodityRepository = new CommodityRepository();


    private CommodityListActivity thisActivity;
    private String from;

    private String qid;
    private String spl;
    private String sph;
    private String skl;
    private String skh;
    private String sti;
    private String sii;
    private String sir;
    private String shl;
    private String shh;
    private String sb;

    private String metal;
    private String craft;
    private String cls;
    private String cle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_list);
        ButterKnife.bind(this);
        initRecycleView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        from = intent.getStringExtra("from");
        if (!(TextUtils.isEmpty(from)) && from.equals("search")) {
            mToolbarCenterTv.setText("搜索结果");
            qid = intent.getStringExtra("qualityId");
            spl = intent.getStringExtra("slpriceLow");
            sph = intent.getStringExtra("slpriceHigh");
            skl = intent.getStringExtra("slkgLow");
            skh = intent.getStringExtra("slkgHigh");
            sti = intent.getStringExtra("styleId");
            sii = intent.getStringExtra("seriesId");
            sir = intent.getStringExtra("slgirard");
            shl = intent.getStringExtra("slhandLow");
            shh = intent.getStringExtra("slhandHigh");
            sb = intent.getStringExtra("slbarcode");
            metal = intent.getStringExtra("metalColor");
            craft = intent.getStringExtra("craft");
            cls = intent.getStringExtra("strChainLength");
            cle = intent.getStringExtra("endChainLength");

            getSearchData(qid, spl, sph, skl, skh, sti, sii, sir, shl, shh, sb, metal, craft, cls, cle);
        } else {
            mToolbarCenterTv.setText(SPUtil.getString("seriesName"));
            reqData();
        }
    }


    private void initRecycleView() {
        thisActivity = this;
        swipeRefreshLayout.setProgressViewOffset(false, 70, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, getResources()
                        .getDisplayMetrics()));
        swipeRefreshLayout.setColorSchemeResources(R.color.black);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!(TextUtils.isEmpty(from)) && from.equals("search")) {
                    getSearchData(qid, spl, sph, skl, skh, sti, sii, sir, shl, shh, sb, metal, craft, cls, cle);
                } else {
                    reqData();
                }

            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    if (thisActivity.hasNext) {
                        boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                        if (isRefreshing) {
                            adapter.notifyItemRemoved(adapter.getItemCount());
                            return;
                        }
                        if (!isLoading) {
                            if (!(TextUtils.isEmpty(from)) && from.equals("search")) {
                                getSearchData(qid, spl, sph, skl, skh, sti, sii, sir, shl, shh, sb, metal, craft, cls, cle);
                            } else {
                                reqData();
                            }

                        }
                    } else {

                    }

                }
            }
        });

        adapter.setOnItemClickListener(new CommodityListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                CommodityListOut.DataBean.ListBean c = data.get(position);
                Intent intent = new Intent(CommodityListActivity.this, GoodsDetailActivity.class);
                BaseParam.setCurrentBarCode( c.getBarCode());
                intent.putExtra("barCode", c.getBarCode());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    public void reqData() {
        Log.i("List", SPUtil.getString("seriesId") + "---" + BaseParam.getDeviceId());
        final LoadingView loadingView = new LoadingView(this);
        loadingView.show();
        commodityRepository.reqGoodsList(pageNum, new RequestCallBack() {
            @Override
            public void onSuccess(Object object) {
                CommodityListOut commodityListOut = (CommodityListOut) object;
                Paginator paginator = commodityListOut.getData().getPaginator();
                if (commodityListOut.getData().getList().size() == 0) {
                    Toast.makeText(CommodityListActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                } else if (thisActivity.hasNext) {
                    data.addAll(commodityListOut.getData().getList());
                    swipeRefreshLayout.setRefreshing(false);
                    adapter.notifyItemRemoved(adapter.getItemCount());
                    thisActivity.pageNum = thisActivity.pageNum + 1;
                    thisActivity.hasNext = paginator.isHasNextPage();
                    adapter.notifyDataSetChanged();
                } else {
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
                swipeRefreshLayout.setRefreshing(false);
                isLoading = false;
                loadingView.dismiss();
            }

            @Override
            public void onFalse(String msg) {
                Toast.makeText(CommodityListActivity.this, msg, Toast.LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
                loadingView.dismiss();
            }
        });
    }

    private void getSearchData(String qid, String spl, String sph, String skl, String skh, String sti, String sii, String sir, String shl, String shh, String sb,
                               String metal, String craft, String cls, String cle

    ) {
        commodityRepository.reqSearchGoodsList(pageNum, qid, spl, sph, skl, skh, sti, sii,
                sir, shl, shh, sb, metal, craft, cls, cle, new RequestCallBack() {
                    @Override
                    public void onSuccess(Object object) {
                        CommodityListOut commodityListOut = (CommodityListOut) object;
                        Paginator paginator = commodityListOut.getData().getPaginator();
                        if (commodityListOut.getData().getList().size() == 0) {
                            Toast.makeText(CommodityListActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else if (thisActivity.hasNext) {
                            data.addAll(commodityListOut.getData().getList());
                            swipeRefreshLayout.setRefreshing(false);
                            adapter.notifyItemRemoved(adapter.getItemCount());
                            thisActivity.pageNum = thisActivity.pageNum + 1;
                            thisActivity.hasNext = paginator.isHasNextPage();
                            adapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(CommodityListActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                            adapter.notifyItemRemoved(adapter.getItemCount());
                        }
                        swipeRefreshLayout.setRefreshing(false);
                        isLoading = false;
                    }

                    @Override
                    public void onFalse(String msg) {
                        Toast.makeText(CommodityListActivity.this, msg, Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }


    @OnClick(R.id.back_img)
    public void onClick() {
        this.finish();
        overridePendingTransition(com.vincent.baseapp.R.anim.fragment_left_in, com.vincent.baseapp.R.anim.fragment_right_out);
    }

}
